<template>
  <div v-loading="loading" class="app-main-content-box">
    <!--filter区域-->
    <div class="filter-content">

      <el-form ref="filterForm" :model="filterForm" label-width="100px" size="small">
        <div class="flexRSS">
          <div>
            <el-form-item
              :rules="[
                { required: true, message: '时间区间不能为空'}
              ]"
              label="投放时间："
              prop="date"
            >
              <el-date-picker
                v-model="filterForm.date"
                :default-time="['00:00:00', '23:59:59']"
                type="datetimerange"
                range-separator="~"
                value-format="yyyy-MM-dd HH:mm:ss"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-form-item>
            <el-form-item label="券码：" prop="couponCode">
              <el-input v-model="filterForm.couponCode" style="width:400px" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="投放方：" prop="merchant">
              <el-select v-model="filterForm.merchant" filterable placeholder="请选择" style="width:400px">
                <el-option label="所有" value="" />
                <el-option
                  v-for="(item, index) in allAuthMchOptions"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </div>
          <div>
            <el-form-item label="券状态：" prop="status">
              <el-select v-model="filterForm.status" filterable placeholder="请选择" style="width:400px">
                <el-option label="所有" value="" />
                <el-option v-for="(v,k) in statusOptions" :key="k" :label="v" :value="k" />
              </el-select>
            </el-form-item>
            <el-form-item label="投放业务：" prop="bizCode">
              <el-select v-model="filterForm.bizCode" filterable placeholder="请选择" style="width:400px">
                <el-option label="所有" value="" />
                <el-option
                  v-for="(item, index) in manageBizCodeOptions"
                  :key="index"
                  :label="item.label"
                  :value="item.key"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="投放来源：" prop="sourceCode">
              <el-select v-model="filterForm.sourceCode" filterable placeholder="请选择" style="width:400px">
                <el-option label="所有" value="" />
                <el-option
                  v-for="(item, index) in sourceCodeOptions"
                  :key="index"
                  :label="item.label"
                  :value="item.key"
                />
              </el-select>
            </el-form-item>
          </div>
        </div>

        <el-form-item class="filter-btn">
          <el-button type="primary" round @click="submitForm">查 询</el-button>
          <el-button round @click="resetForm">重 置</el-button>
          <!-- <el-button v-if="!$store.getters.banBtnList.includes('BTN_COUPON_RECEIVE_DETAIL_EXPORT')" round @click="downExcel">导 出</el-button> -->
        </el-form-item>
      </el-form>
    </div>

    <AppTableStatisticsCard :statistics-card-data="statisticsCardData" :cols="[8,8,8,8,8]" />

    <div class="table-content">
      <el-table :data="list" size="small" border stripe style="width: 100%" empty-text="暂无数据">
        <el-table-column prop="couponCode" label="券码" fixed="left" />
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <span>{{ statusOptions[scope.row.status] }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="expireTime" label="有效期">
          <template slot-scope="scope">
            <div>开始：{{ scope.row.effectiveTime }}</div>
            <div>结束：{{ scope.row.expireTime }}</div>
          </template>
        </el-table-column>
        <!--        <el-table-column prop="couponCode" label="投放业务/投放来源/业务订单号">-->
        <el-table-column label="投放业务/投放来源">
          <template slot="header" slot-scope="scope">
            <div>投放业务 / 投放来源</div>
          </template>
          <template slot-scope="scope">
            <div>{{ (bizCodeKeyOptions[scope.row.bizCode]||'无')+' / '+(sourceCodeKeyOptions[scope.row.sourceCode]||'无') }}</div>
          </template>
        </el-table-column>
        <el-table-column label="投放方/投放时间">
          <template slot="header" slot-scope="scope">
            <div>投放方</div>
            <div>投放时间</div>
          </template>
          <template slot-scope="scope">
            <div>{{ scope.row.merchantName }}</div>
            <div>{{ scope.row.createTime }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="customerName" label="顾客" />
        <el-table-column prop="remark" label="备注" />

      </el-table>
      <!-- 分页 -->
      <pagination-direction
        v-if="paginationConfig.total!==0"
        :config="paginationConfig"
        @sizeschange="sizesChange"
        @pagechange="pageChange"
      />
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { couponIssueCount, couponIssueList } from '../../../api/coupon'
import { authMerchants } from '../../../api/mch'

export default {
  props: {
    couponBase: {
      require: true,
      type: Object
    }
  },
  data() {
    return {
      // 配置
      // 分页配置
      paginationConfig: {
        direction: 'center', // 分页位置
        layout: 'total, sizes, prev, pager, next, jumper', // 分页类型
        pageSizes: [10, 20], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10 // 每页条数-默认10
      },
      statusOptions: {
        1: '待使用',
        2: '已核销',
        3: '已过期',
        4: '待使用(锁定中)'
      },
      allAuthMchOptions: [],
      // 状态
      loading: false,
      // 数据
      statisticsCardData: [],
      list: [],
      filterForm: {
        date: [
          this.$momentMini().format('YYYY-MM-DD') + ' 00:00:00',
          this.$momentMini().format('YYYY-MM-DD') + ' 23:59:59'
        ],
        start: null,
        end: null,
        couponCode: '',
        bizCode: '',
        sourceCode: '',
        couponId: '',
        merchant: '',
        status: ''
      }
    }
  },
  computed: {
    ...mapGetters([
      'manageBizCodeOptions',
      'bizCodeKeyOptions',
      'sourceCodeOptions',
      'sourceCodeKeyOptions'
    ])
  },
  watch: {},
  created() {
  },
  mounted() {
    this.getAuthMerchants()
    this.fetchData()
  },
  methods: {
    /**
     * 数据组
     */
    // 获取列表
    fetchData(
      page = this.paginationConfig.page,
      pageSize = this.paginationConfig.pageSize
    ) {
      this.$refs.filterForm.validate((valid) => {
        if (valid) {
          let params = {}
          params = Object.assign({}, this.filterForm)
          params.page = page
          params.pageSize = pageSize
          params.start = params.date[0]
          params.end = params.date[1]
          params.couponId = this.couponBase.id
          delete params.date
          // 清除多余字段
          for (const key in params) {
            if (params[key] === '' || params[key] === 'all') {
              delete params[key]
            }
          }
          this.loading = true
          Promise.all([this.getList(params), this.getCount(params)]).then(
            (res) => {
              this.loading = false
            }
          )
        }
      })
    },

    // 获取列表
    getList(params) {
      return new Promise((resolve, reject) => {
        couponIssueList(params)
          .then((res) => {
            this.list = res.data.list
            this.paginationConfig.total = res.data.total
            this.paginationConfig.page = res.data.pageNum
          })
          .finally(() => {
            resolve()
          })
      })
    },

    // 获取统计
    getCount(params) {
      return new Promise((resolve, reject) => {
        if (params.page !== 1) {
          resolve()
        } else {
          this.statisticsCardData = [
            {
              title: '已发放 / 张',
              value: 0,
              describeList: [],
              detailList: []
            }
            // {
            //   title: '待使用 / 张',
            //   value: 0,
            //   describeList: ['待使用优惠券包含被未支付订单锁定的优惠券'],
            //   detailList: []
            // },
            // {
            //   title: '已核销 / 张',
            //   value: 0,
            //   describeList: [],
            //   detailList: []
            // },
            // {
            //   title: '已过期 / 张',
            //   value: 0,
            //   describeList: ['用户未使用导致过期的券'],
            //   detailList: []
            // }
          ]
          couponIssueCount(params)
            .then((res) => {
              let allCount = 0
              let validCount = 0
              res.data.forEach((v) => {
                switch (v.status) {
                  case 1:
                    allCount += v.num
                    validCount += v.num
                    break
                  case 2:
                    allCount += v.num
                    // this.statisticsCardData[2].value = v.num
                    if (v.num) this.statisticsCardData[0].detailList.push(`含 ${v.num} 张已核销`)
                    break
                  case 3:
                    allCount += v.num
                    // this.statisticsCardData[3].value = v.num
                    if (v.num) this.statisticsCardData[0].detailList.push(`含 ${v.num} 张因未使用已过期`)
                    break
                  case 4:
                    allCount += v.num
                    validCount += v.num
                    // this.statisticsCardData[1].describeList.push(
                    //   `(含锁定中：${v.num}/张)`
                    // )
                    break
                }
              })
              this.statisticsCardData[0].value = allCount
              // this.statisticsCardData[1].value = validCount
              if (validCount) this.statisticsCardData[0].detailList.push(`含 ${validCount} 张未使用（包含未支付订单锁定的券）`)
            })
            .finally(() => {
              resolve()
            })
        }
      })
    },

    // 获取合作商户
    getAuthMerchants() {
      return new Promise((resolve) => {
        authMerchants({ belongMerchant: this.couponBase.belongMerchant }).then(res => {
          // const allMchList = []
          // res.data.forEach(v => {
          //   // v.id = 'M-' + v.id
          //   allMchList.push(
          //     {
          //       id: v.id,
          //       name: v.name,
          //       shops: []
          //     }
          //   )
          // })
          this.allAuthMchOptions = res.data
        }).finally(() => {
          resolve()
        })
      })
    },

    // 获取列表
    /**
     * 按钮组
     */
    // 分页sizes改变
    sizesChange() {
      this.fetchData()
    },

    // 分页page改变
    pageChange() {
      this.fetchData()
    },

    // 查询
    submitForm() {
      this.fetchData(1)
    },

    // 重置
    resetForm() {
      this.$refs.filterForm.resetFields()
    }
    /**
     * 状态组
     */
    /**
     * 方法组
     */
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
/* 筛选 */
.filter-container {
  .filter-btn {
    margin-bottom: 20px;
  }

  .check-all {
    margin-right: 30px;
  }

  // 单选换行
  .el-radio + .el-radio {
    margin-left: 0;
  }

  .el-radio {
    margin-right: 10px;
    height: 32px;
    line-height: 32px;
  }
}

/* 表格 */
.table-content {
  margin-top: 10px;
}
</style>
